import count from '@feidao/web/atom/nodejs/db/count';
import query from '@feidao/web/atom/nodejs/db/query';
import { IBaseTable } from '@feidao/web/atom/nodejs/db/interfaces';
import log from '@feidao/web/atom/nodejs/logger/log';

interface Message {
	systemid1: string;
	systemid2: string;
	man?: boolean;
}

interface Star extends IBaseTable {
	name: string;
	sex: 0 | 1;
}

interface Works extends IBaseTable {
	star: string;
	works: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const { systemid1, systemid2 } = msg;
	const { exec, prepare } = query(action_id, session_id, spaceid, systemid1);
	prepare('star', ['_id', 'name'], { sex: msg.man ? 1 : 0 });
	const [stars] = await exec();
	const m = new Map<string, string>();
	const star_ids = (stars as Star[]).map((s) => {
		const id = s._id;
		m.set(id, s.name);
		return id;
	});
	const { exec: e2, prepare: p2 } = query(action_id, session_id, spaceid, systemid2);
	const q = {
		star: {
			$in: star_ids
		}
	};
	// { $regex: '.*' + name + '.*', $options: 'i' } // 模糊查询
	p2('works', ['star', 'works'], q, 20, 1);
	const [all_works] = (await e2()) as [Works[]];
	const works_count = await (async () => {
		if (all_works.length < 20) {
			return all_works.length;
		} else {
			const { exec: e3, prepare: p3 } = count(action_id, session_id, spaceid, '2000');
			p3('works', q);
			const [n] = await e3();
			return n;
		}
	})();
	const works = all_works.map((work) => {
		const { star: id, works: w } = work;
		return {
			star: m.get(id),
			works: w
		};
	});
	log('success');
	return {
		works,
		works_count
	};
}
